package org.grow.loginto.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.grow.loginto.dao.UserInfoDao;
import org.grow.loginto.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 21-6-2
 */
@Service
public class HotLoginHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        System.out.println(e.getClass());
//     账号被冻结   DisabledException
//     用户名密码不对   BadCredentialsException
//        InternalAuthenticationServiceException
        e.printStackTrace();
        response.setStatus(960);
        response.getWriter().println(
                objectMapper.writeValueAsString(e.getMessage()+" AuthFailure")
        );

    }
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        System.out.println("login success already");
        System.out.println("principal"+auth.getPrincipal());
        System.out.println("auths"+auth.getAuthorities());
        UserInfo userInfo = (UserInfo) auth.getPrincipal();
        System.out.println("此时的Filter Enconding "+response.getCharacterEncoding());
        userInfo.setLastLoginTime(LocalDateTime.now());
        userInfoDao.save(userInfo);
//        response.setCharacterEncoding("utf8");
        response.setStatus(200);
        response.getWriter().println(
                objectMapper.writeValueAsString(userInfo));
        response.getWriter().flush();
    }
}
